//
//  KYADLaunch.m
//  KYKJPackDemo
//
//  Created by 罗新 on 2017/11/10.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "KYADLaunch.h"
#import "JSTAdWebViewController.h"
static float pathValue = 0.;
typedef void(^touchOffBlock)();
typedef void(^touchChangeBlock)();


@interface KYADLaunch ()
@property (nonatomic, strong) UIWindow* window;
@property (nonatomic, assign) NSInteger downCount;
@property (nonatomic, weak) UIButton* downCountButton;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) UILabel *label;

@property (nonatomic, strong) touchOffBlock endBlock;

@property (nonatomic, strong) touchChangeBlock changePageBlock;

@property (nonatomic, strong) JSTHomePageModel *model;

@property (nonatomic, strong) UIImageView *adImgView;

@property (nonatomic, strong) UIImageView *otherImgView;

@property (nonatomic, strong) JSTLoopProgressView *loopProgressView;


@end
@implementation KYADLaunch
+ (void)load
{
    [self shareInstance];
}
+ (instancetype)shareInstance
{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        
        ///如果是没啥经验的开发，请不要在初始化的代码里面做别的事，防止对主线程的卡顿，和 其他情况
        
        ///应用启动, 首次开屏广告
        [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidFinishLaunchingNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
            ///要等DidFinished方法结束后才能初始化UIWindow，不然会检测是否有rootViewController
            [self checkAD];
        }];
        /*
        ///进入后台
        [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
            [self request];
        }];
        ///后台启动,二次开屏广告
        
        [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillEnterForegroundNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
            [self checkAD];
        }];
         */
    }
    return self;
}
- (void)request
{
    ///.... 请求新的广告数据
}
- (void)checkAD
{
    ///如果有则显示，无则请求， 下次启动再显示。
    ///我们这里都当做有
    [self show];
}
- (void)show
{
    ///初始化一个Window， 做到对业务视图无干扰。
    UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    window.rootViewController = [UIViewController new];
    window.rootViewController.view.backgroundColor = [UIColor clearColor];
    window.rootViewController.view.userInteractionEnabled = NO;
    ///广告布局
    [self setupSubviews:window];
    
    ///设置为最顶层，防止 AlertView 等弹窗的覆盖
    window.windowLevel = UIWindowLevelStatusBar + 1;
    
    ///默认为YES，当你设置为NO时，这个Window就会显示了
    window.hidden = NO;
    window.alpha = 1;
    
    ///防止释放，显示完后  要手动设置为 nil
    self.window = window;
}

- (void)letGo
{
    ///不直接取KeyWindow 是因为当有AlertView 或者有键盘弹出时， 取到的KeyWindow是错误的。
    UIViewController* rootVC = [[UIApplication sharedApplication].delegate window].rootViewController;
//    [[rootVC imy_navigationController] pushViewController:[IMYWebViewController new] animated:YES];
    
    [self hide];
}
- (void)goOut
{
    [self hide];
}
- (void)hide
{
    ///来个渐显动画
    [UIView animateWithDuration:0.3 animations:^{
        self.window.alpha = 0;
    } completion:^(BOOL finished) {
        [self.window.subviews.copy enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromSuperview];
        }];
        self.window.hidden = YES;
        self.window = nil;
    }];
}

///初始化显示的视图， 可以挪到具
- (void)setupSubviews:(UIWindow*)window
{
    NSArray *data = [JSTFMDBManager querySqlforTab:[JSTStartViewData modelWith:nil adImgUrl:nil disseminateImgUrl:nil]];
    if (data.count != 0) {
        JSTStartViewData *model = data[0];
        if (IsStrEmpty(model.adImgUrl) || IsStrEmpty(model.disseminateImgUrl)){
            ((AppDelegate *)[UIApplication sharedApplication].delegate).startViewNeedOpen = YES;
            return;
        }
        [self.adImgView sd_setImageWithURL:[NSURL URLWithString:model.adImgUrl] placeholderImage:nil options:SDWebImageAllowInvalidSSLCertificates];
        [self.otherImgView sd_setImageWithURL:[NSURL URLWithString:model.disseminateImgUrl] placeholderImage:nil options:SDWebImageAllowInvalidSSLCertificates];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSDictionary * stataDic = [userDefaults valueForKey:@"tableScreenData"];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"event"] = @"view";
        [JSTServer requestPostStatisticsData:dict postInterface:stataDic[@"url"] dataDic:nil errorStr:nil];
    }else {
        end();
        [self hide];
        ((AppDelegate *)[UIApplication sharedApplication].delegate).startViewNeedOpen = YES;
        return;
    }
    [self addSubview:self.adImgView];
    [self addSubview:self.otherImgView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changePage)];
    [self.adImgView addGestureRecognizer:tap];
    [self createTimer];
    self.endBlock = ^(){
        end();
    };
    self.changePageBlock = ^(){
        changPage();
    };
    [self addSubview:self.loopProgressView];
    UITapGestureRecognizer *hopTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endCurrentPage)];
    [self.loopProgressView addGestureRecognizer:hopTap];
}


- (void) endCurrentPage{
    [_timer invalidate];
    _timer = nil;
    if (_endBlock) {
        _endBlock();
    }
    [self removeFromSuperview];
}

- (void) createTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(downloadCurrent) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

- (void) downloadCurrent {
    pathValue += .1/5.;
    [self.loopProgressView drawProgress:pathValue];
    if (pathValue >= 1.) {
        [_timer invalidate];
        _timer = nil;
        if (_endBlock) {
            _endBlock();
        }
        [self removeFromSuperview];
    }
}

- (void) changePage {
    [_timer invalidate];
    _timer = nil;
    if (_changePageBlock) {
        _changePageBlock();
    }
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary * currentDic = [userDefaults valueForKey:@"tableScreenData"];
    [_model createOtherAdvertOclick:currentDic];
    JSTAdWebViewController *webView = [[JSTAdWebViewController alloc] init];
    webView.urlStr = currentDic[@"url"];
    webView.pushData = currentDic;
    [[self getViewCtl].navigationController pushViewController:webView animated:YES];
    [self removeFromSuperview];
}

- (UIViewController *) getViewCtl{
    for (UIView *next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

- (JSTLoopProgressView *)loopProgressView
{
    if (!_loopProgressView) {
        _loopProgressView = [[JSTLoopProgressView alloc] init];
        _loopProgressView.frame = CGRectMake(kDeviceWidth - kCurrentScreenWidth(10) - kCurrentScreenWidth(50), kCurrentScreenWidth(20), kCurrentScreenWidth(50), kCurrentScreenWidth(50));
        _loopProgressView.layer.masksToBounds = YES;
        _loopProgressView.layer.cornerRadius = kCurrentScreenWidth(50)/2.;
    }
    return _loopProgressView;
}

- (UIImageView *)adImgView
{
    if (!_adImgView) {
        _adImgView = [[UIImageView alloc] init];
        _adImgView.userInteractionEnabled = YES;
        _adImgView.frame = CGRectMake(0, 0, kDeviceWidth, kDeviceHeight - kDeviceWidth*200/750.);
        _adImgView.myLeftMargin = _adImgView.myRightMargin = 0;
    }
    return _adImgView;
}

- (UIImageView *)otherImgView{
    if (!_otherImgView) {
        _otherImgView = [[UIImageView alloc] init];
        _otherImgView.frame = CGRectMake(0, CGRectGetMaxY(self.adImgView.frame), kDeviceWidth, kDeviceWidth*200/750.);
        _otherImgView.myLeftMargin = _otherImgView.myRightMargin = 0;
    }
    return _otherImgView;
}
@end


@interface JSTLoopProgressView()
@property (nonatomic, assign) CGFloat progress;
@property (nonatomic, strong) CAShapeLayer *progressLayer;
@end
@implementation JSTLoopProgressView

- (UILabel *)label
{
    if (_label == nil) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(2.5, 2.5, self.width - 2.5*2, self.height - 2.5*2)];
        label.textAlignment = NSTextAlignmentCenter;
        label.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
        label.text = @"跳过";
        label.font = kSystemFont(self.width/4.);
        label.textColor = [UIColor whiteColor];
        [self addSubview:label];
        _label = label;
    }
    return _label;
}

- (void)drawProgress:(CGFloat )progress
{
    _progress = progress;
    _progressLayer.opacity = 0;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    
    [self drawCycleProgress];
    [self label];
}

- (void)drawCycleProgress
{
    CGPoint center = CGPointMake(kCurrentScreenWidth(50)/2., kCurrentScreenWidth(50)/2.);
    CGFloat radius = kCurrentScreenWidth(48)/2.;
    CGFloat startA = - M_PI_2;
    CGFloat endA = -M_PI_2 + M_PI * 2 * _progress;
    _progressLayer = [CAShapeLayer layer];
    _progressLayer.frame = self.bounds;
    _progressLayer.fillColor = [[UIColor clearColor] CGColor];
    _progressLayer.strokeColor = [[UIColor redColor] CGColor];
    _progressLayer.opacity = 1;
    _progressLayer.lineCap = kCALineCapRound;
    _progressLayer.lineWidth = 2.5;
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    _progressLayer.path =[path CGPath];
    [self.layer addSublayer:_progressLayer];
}

@end
